/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.TbCategory;
import com.thinkgem.jeesite.modules.sys.service.TbCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

import static com.thinkgem.jeesite.modules.sys.entity.TbCategory.sortList;

;

/**
 * 商品分类Controller
 * @author ThinkGem
 * @version 2013-3-23
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/category")
public class ProductCategoryController extends BaseController {

	@Autowired
	private TbCategoryService tbcategoryService;
	
	@RequestMapping(value = "list")
	public String list(Model model) {
		List<TbCategory> list = Lists.newArrayList();
		List<TbCategory> sourcelist = tbcategoryService.findAllTbCategory();
		TbCategory.sortList(list, sourcelist, TbCategory.getRootId(), true);
        model.addAttribute("list", list);
		return "modules/sys/categoryList";
	}
	@RequestMapping(value = "toform")
	public String toform(TbCategory category, Model model) {
		model.addAttribute("category", category);
		return "modules/sys/categoryForm";
	}
	@RequestMapping(value = "form")
	public String form(TbCategory category, Model model) {
		if (category.getParent()==null|| category.getParent().getId()==null){
			category.setName(tbcategoryService.getTbCategory(category.getId()).getName());
			category.setParent(new TbCategory(tbcategoryService.getTbCategory(category.getId()).getParentId()));
			if (tbcategoryService.getTbCategory(category.getId()).getParentIds()!=null){
				category.setParentIds(tbcategoryService.getTbCategory(category.getId()).getParentIds());
			}
			if (tbcategoryService.getTbCategory(category.getId()).getRemarks()!=null){
				category.setRemarks(tbcategoryService.getTbCategory(category.getId()).getRemarks());
			}
		}
		category.setParent(tbcategoryService.getTbCategory(category.getParent().getId()));
		// 获取排序号，最末节点排序号+30
		if (StringUtils.isBlank(category.getId())){
			List<com.thinkgem.jeesite.modules.sys.entity.TbCategory> list = Lists.newArrayList();
			List<com.thinkgem.jeesite.modules.sys.entity.TbCategory> sourcelist = tbcategoryService.findAllTbCategory();
			sortList(list, sourcelist, category.getParentId(), false);
			if (list.size() > 0){
				category.setSort(list.get(list.size()-1).getSort() + 30);
			}
		}
		model.addAttribute("category", category);
		return "modules/sys/categoryForm";
	}

	@RequestMapping(value = "save")
	public String save(TbCategory TbCategory, Model model, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/tbCategory/";
		}
		tbcategoryService.saveTbCategory(TbCategory);
		addMessage(redirectAttributes, "保存菜单'" + TbCategory.getName() + "'成功");
		return "redirect:" + adminPath + "/sys/category/list";
	}

	@RequestMapping(value = "delete")
	public String delete(TbCategory TbCategory, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/category/list";
		}
		if(!TbCategory.getId().equals("2")&!TbCategory.getId().equals("3")& !TbCategory.getId().equals("4")){

			tbcategoryService.deleteTbCategory(TbCategory);
			addMessage(redirectAttributes, "删除菜单成功");
		}else{
			addMessage(redirectAttributes, "类别不可删除，不允许操作！");
			return "redirect:" + adminPath + "/sys/category/list";
		}
//		}
		return "redirect:" + adminPath + "/sys/category/list";
	}

	@RequestMapping(value = "tree")
	public String tree() {
		return "modules/sys/categoryTree";
	}

	@RequestMapping(value = "treeselect")
	public String treeselect(String parentId, Model model) {
		model.addAttribute("parentId", parentId);
		return "modules/sys/categoryTreeselect";
	}
	
	/**
	 * 批量修改菜单排序
	 */
	@RequestMapping(value = "updateSort")
	public String updateSort(String[] ids, Integer[] sorts, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/category/list";
		}
    	for (int i = 0; i < ids.length; i++) {
    		TbCategory TbCategory = new TbCategory(ids[i]);
    		TbCategory.setSort(sorts[i]);
    		tbcategoryService.updateTbCategorySort(TbCategory);
    	}
    	addMessage(redirectAttributes, "保存菜单排序成功!");
		return "redirect:" + adminPath + "/sys/category/list";
	}
	
	/**
	 *代理商只能添加便利到家和生活预定的商品种类，将海外预定从列表中移除
	 */
	@ResponseBody
	@RequestMapping(value = "treeData1")
	public List<Map<String, Object>> treeData1(@RequestParam(required=false) String extId,@RequestParam(required=false) String isShowHide, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<TbCategory> list = tbcategoryService.findAllTbCategory();
	/*	for (int i=0; i<list.size(); i++){
			TbCategory e = list.get(i);
			if(e.getId().equals("2")||e.getParentId().equals("2")){
				list.remove(i);
				i--;
			}
		}*/

		for (int i=0; i<list.size(); i++){
			TbCategory e = list.get(i);
			if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){
				if(isShowHide != null && isShowHide.equals("0") && e.getIsShow().equals("0")){
					continue;
				}

				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("name", e.getName());
				mapList.add(map);

			}
		}
		return mapList;
	}
	/**
	 *海外店铺只能添加海外订购商品类型
	 */
	@ResponseBody
	@RequestMapping(value = "treeData2")
	public List<Map<String, Object>> treeData2(@RequestParam(required=false) String extId,@RequestParam(required=false) String isShowHide, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<TbCategory> list = tbcategoryService.findAllTbCategory();
		for (int i=0; i<list.size(); i++){
			TbCategory e = list.get(i);
			if(e.getId().equals("1")||e.getId().equals("3")||e.getParentId().equals("3")||e.getId().equals("4")||e.getParentId().equals("4")){
				list.remove(i);
				i--;
			}else if(e.getParentIds().length()>5){
				String parIds = e.getParentIds().substring(4,5);
				if("3".equals(parIds)||"4".equals(parIds)){
					list.remove(i);
					i--;
				}
			}
		}

		for (int i=0; i<list.size(); i++){
			TbCategory e = list.get(i);
			if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){
				if(isShowHide != null && isShowHide.equals("0") && e.getIsShow().equals("0")){
					continue;
				}

				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("name", e.getName());
				mapList.add(map);

			}
		}
		return mapList;
	}
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId,@RequestParam(required=false) String isShowHide, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<TbCategory> list = tbcategoryService.findAllTbCategory();
		for (int i=0; i<list.size(); i++){
			TbCategory e = list.get(i);
			if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){
				if(isShowHide != null && isShowHide.equals("0") && e.getIsShow().equals("0")){
					continue;
				}
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return mapList;
	}
	//验证类别名称是否唯一
	@RequestMapping("/checkCategory")
	public void checkBarcode(HttpServletRequest request, HttpServletResponse response, String category) {
		response.setContentType("text/html;charset=UTF-8");
		//根据reverflag，查询该商品所属类别
		//根据条形码和是否是预定决定该商品为哪种商品
		TbCategory tbCategory =tbcategoryService.checkTbCategory(category);
		try {
			if (tbCategory != null) {
				response.getWriter().print("1");
			} else {
				response.getWriter().print("0");
			}
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@RequestMapping("/getParCategory")
	@ResponseBody
	public void getParCategory(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("text/html;charset=UTF-8");
		TbCategory tbCategory =tbcategoryService.getTbCategory(request.getParameter("categoryId"));
		try {
			String a = tbCategory.getParentIds().substring(4,5);
			if ("3".equals(a)) {//3是生活预定大类id  4是便利生活大类id
				response.getWriter().print("3");
			} else {
				response.getWriter().print("4");
			}
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
